import { reactive } from "vue";
import { login, me } from "@/api/auth/user";
import router from "@/router";
import { useCurrentUserStore } from "@/stores/currentUser";
import { storeToRefs } from "pinia";

const store = useCurrentUserStore();
const { isLogin } = storeToRefs(store);

export const _$ = reactive({
  login: {
    rules: reactive({
      username: [
        { required: true, message: "用户账号不能为空", trigger: "blur" },
        {
          min: 3,
          max: 16,
          message: "用户账号长度必须在3到16位之间",
          trigger: "change",
        },
      ],
      password: [
        { required: true, message: "密码不能为空", trigger: "change" },
      ],
    }),
    requestParam: {
      username: "",
      password: "",
      isAdmin: true,
    },
    responseParam: {},
  },
  roles: [
    {
      label: "管理员",
      value: true,
    },
    {
      label: "普通用户",
      value: false,
    },
  ],
});

export const $ = {
  onSubmit(formRef) {
    if (!formRef) {
      return;
    }

    login(_$.login.requestParam)
      .then((login_result) => {
        localStorage.setItem("ats-user-token", login_result);
      })
      .then((_) => {
        me().then((data) => {
          localStorage.setItem("ats-user-info", JSON.stringify(data));
          localStorage.setItem("ats-user-userType", data.userType);
          localStorage.setItem("ats-user-headImage", data.headImage);
          isLogin.value = true;
          formRef.resetFields();
          if (data.userType === "ADMIN") {
            router.push("/manage/index");
          } else {
            router.push("/portal/home");
          }
        });
      })
      .catch((err) => {
        console.error(err);
      });
  },

  clean() {
    _$.login.responseParam = {
      username: "",
      password: "",
      isAdmin: null,
    };
  },
};

export const to = {
  toRegister() {
    router.push("/register");
  },

  toFindPwd() {
    router.push("/find-pwd");
  },

  // toCheckAndRedirectToFindPwd(username) {
  //   axios.get('/api/findSecurityQuestion', { params: { username } })
  //     .then(response => {
  //       if (response.data === "未设置密保问题。") {
  //         this.$message.warning("未设置密保问题，无法使用该功能。");
  //       } else {
  //         // 将问题传递给找回密码页面
  //         router.push({ name: 'find-pwd', query: { question: response.data, username } });
  //       }
  //     })
  //     .catch(error => {
  //       console.error('检查密保问题时出错:', error);
  //       this.$message.error("系统错误，请稍后再试。");
  //     });
};
